package com.itcpeng.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itcpeng.pojo.Permission;
import com.itcpeng.pojo.Role;
import com.itcpeng.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service("springSecurity")
public class SpringSecurityUserServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //认证
        //通过用户名查询用户是否存在数据库,(调用业务)
        User user = userService.findByUserName(s);
        //如果用户名为空  返回null
        if (user == null) {
            return null;
        }
        //如果不为空   授权
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        //用户拥有的角色
        Set<Role> userRoles = user.getRoles();
        if (userRoles != null) {
            GrantedAuthority authority = null;
            for (Role role : userRoles) {
                //创建角色
                authority = new SimpleGrantedAuthority(role.getKeyword());
                //添加角色
                list.add(authority);
                //判断角色下是否有权限
                if (role.getPermissions() != null) {
                    for (Permission permission : role.getPermissions()) {
                        //添加用户权限
                        authority = new SimpleGrantedAuthority(permission.getKeyword());
                        //添加用户权限
                        list.add(authority);
                    }
                }
            }
        }
        //让security帮我校验
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);
    }
}
